package com.synthefact.daj.view.awt;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Window;
import java.util.StringTokenizer;


public class Popup extends Window {

    private Visualizer visualizer;
    private FontMetrics fontMetrics;
    private int fontHeight;
    private int fontAscent;
    private int fontAdvance;
    private String text;
    private int frameX;
    private int frameY;
    private int frameWidth;
    private int frameHeight;
    private int textX;
    private int textY;

    public Popup(Visualizer visual) {
	super(visual);
	setVisible(false);
	visualizer = visual;
	// determine window font and color
	Font font = new Font("Helvetica", Font.PLAIN, 12);
	Color color = new Color(255, 255, 204);
	setFont(font);
	setBackground(color);
	// remember metrices
	fontMetrics = getFontMetrics(font);
	fontHeight = fontMetrics.getHeight();
	fontAscent = fontMetrics.getAscent();
	fontAdvance = 2;
    }

    // --------------------------------------------------------------------------
    // let window pop up at `xpos/ypos` showing `txt`
    // --------------------------------------------------------------------------
    public void popup(int xpos, int ypos, String txt) {
	// store text
	text = txt;
	// determine window dimensions
	StringTokenizer t = new StringTokenizer(text, "\n");
	int num = t.countTokens();
	int height = num * fontHeight + 2;
	int width = 0;
	for (int i = 0; i < num; i++) {
	    String string = t.nextToken();
	    int width0 = fontMetrics.stringWidth(string);
	    if (width0 > width)
		width = width0;
	}
	width += 2 * (1 + fontAdvance);
	// determine frame coordinates
	frameX = 0;
	frameY = 0;
	frameWidth = width - 1;
	frameHeight = height - 1;
	// determine text coordinates
	textX = 1 + fontAdvance;
	textY = 1 + fontAscent;

	// position window and show it
	setLocation(xpos, ypos);
	setSize(width, height);
	setVisible(true);
    }

    public void paint(Graphics g) {
	g.setColor(Color.black);
	g.drawRect(frameX, frameY, frameWidth, frameHeight);
	StringTokenizer t = new StringTokenizer(text, "\n");
	int num = t.countTokens();
	for (int i = 0; i < num; i++) {
	    String string = t.nextToken();
	    g.drawString(string, textX, textY + i * fontHeight);
	}
    }
}
